package com.example.sell_qq.util;

import android.os.StrictMode;
import android.util.Log;

import com.example.sell_qq.vo.ResponseVO;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtils {
    private static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    public static String httpJsonPost(String url, String json) throws IOException {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String httpFormPost(String url, RequestBody data) throws IOException {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(data)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String httpGet(String url) throws IOException {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            Log.d("get response", "response.code()==" + response.code());
            Log.d("get response", "response.message()==" + response.message());
            return response.body().string();
        }
    }

    public static ResponseVO resolveResponse(String response) {
        ResponseVO responseVO;
        Gson gson = new Gson();

        responseVO = gson.fromJson(response, ResponseVO.class);

        return responseVO;
    }
}